<template>
  <div class="content">
    <div class="breadcrumb" :gutter="24">
      <el-form ref="form" :model="formData" label-width="120px" size="small">
        <el-row :gutter="28">
          <el-col :xs="9" :sm="6" :md="5" :lg="5" :xl="4">
            <el-form-item :label="$t('system.user_name')">
              <el-input v-model="formData.keyWord" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2">
            <el-form-item label-width="0px">
              <el-button type="primary" size="small" @click="handleSearch()">{{ $t("common.query") }}</el-button>
            </el-form-item>
          </el-col>
          <div class="btngroup">
            <el-button type="primary" size="small" @click="handleAdd()">{{ $t("common.add") }}</el-button>
            <el-button type="primary" size="small" @click="handleEdit()">{{ $t("common.edit") }}</el-button>
            <el-button type="primary" size="small" @click="handleDel()">{{ $t("common.remove") }}</el-button>
          </div>
        </el-row>
      </el-form>

    </div>

    <div class="tableAuto" style="clear:both">
      <el-table :data="tableData" style="width:100%" :height="height" @row-click="rowClick" border stripe
        :header-cell-style="{background:'#EAEBEC'}" v-loading="tableLoading" ref="refTable" highlight-current-row @sort-change='sortChange'>
        <el-table-column label="" width="50" align="center">
          <template slot-scope="scope">
            <div>
              <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" :label="$t('common.number')" align="center" width="75">
          <template slot-scope="scope">
            {{table_index(scope.$index+1)}}
          </template>
        </el-table-column>
        <el-table-column prop="faccount" width="150" show-overflow-tooltip :label="$t('common.user_name')"
          sortable='custom'></el-table-column>
        <el-table-column prop="frealName" width="150" show-overflow-tooltip :label="$t('common.full_name')"
          sortable='custom'></el-table-column>
        <el-table-column prop="fsignature" width="100" show-overflow-tooltip :label="$t('system.is_it_valid')">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.fsignature" :disabled="disabled" active-color="#00A09D"
              @change="handleSwitch(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="fdescription" show-overflow-tooltip :label="$t('basic.remarks')"></el-table-column>
      </el-table>
    </div>

    <div class="pagination-area">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[20, 30, 50, 100]"
        :page-size="pager.pageSize" :current-page="pager.pageNum" layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
      </el-pagination>
    </div>

    <el-dialog v-dialogDrag :title="title" :visible.sync="isShowAdd" :close-on-click-modal="false" width="35%" :before-close="handleClose">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="85px" size="small" :hide-required-asterisk="true">
        <el-row :gutter="24">
          <el-col :xs="24">
            <el-form-item :label="$t('common.full_name')" prop="frealName">
              <el-input v-model="ruleForm.frealName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('common.user_name')" prop="faccount">
              <el-input v-model="ruleForm.faccount" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('system.password')" prop="fpsw">
              <!-- <input style="opacity: 0;position:absolute;width:0;height:0;">
                            <input type="password" style="opacity: 0;position:absolute;width:0;height:0;"> -->
              <el-input type="password" v-model="ruleForm.fpsw" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('system.confirm_pwd')" prop="confirmFpsw">
              <el-input type="password" v-model="ruleForm.confirmFpsw" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24">
                         <el-form-item label="是否管理员" prop="fisAdministrator" class="adminSelect">
                            <el-select v-model="ruleForm.fisAdministrator" placeholder="请选择">
                                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                     </el-col> -->
          <el-col :xs="24">
            <el-form-item :label="$t('system.is_it_valid')" prop=" fsignature" class="adminSelect">
              <el-select v-model="ruleForm.fsignature" placeholder="">
                <el-option v-for="item in isvalidList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.remarks')">
              <el-input type="textarea" :rows="3" v-model="ruleForm.fdescription" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :loading="loading"
          @click="handleConfirm('ruleForm')">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { userAdmin } from "@/api/userAdmin"
import { siteConfig } from "@/api/siteConfig";
export default {
  data () {
    let fpsw = (rule, value, callback) => {
      if (!value) {
        callback(new Error('密码不能为空'));
      } else {

        console.log(this.formCofig)

        if (value != this.oldPassWord) {
          console.log(this.formCofig.passwordRules.indexOf("2"))
          let min = this.formCofig.passwordRules.indexOf("2") > -1 ? '(?=.*[a-z])' : "";
          let max = this.formCofig.passwordRules.indexOf("1") > -1 ? '(?=.*[A-Z])' : "";
          let num = this.formCofig.passwordRules.indexOf("3") > -1 ? '(?=.*\\d)' : "";
          let patrn = this.formCofig.passwordRules.indexOf("4") > -1 ? '(?=.*[^a-zA-Z0-9_])[\\S]' : "";

          let reg = eval("/^" + min + max + num + patrn + "{" + this.formCofig.passwordLength + ",}" + "/g;");
          console.log(reg)
          console.log(value)
          if (!reg.test(value)) {
            let reginfo = '至少' + this.formCofig.passwordLength + '个字符';
            this.formCofig.passwordRules.forEach(item => {
              switch (item) {
                case "1":
                  reginfo += ',1位大写字母';
                  break;
                case "2":
                  reginfo += ',1位小写字母';
                  break;
                case "3":
                  reginfo += ',1位数字;';
                  break;
                case "4":
                  reginfo += ',1位特殊字段';
                  break;
              }
            })
            console.log(reginfo)
            callback(new Error(reginfo));
          } else if (value.length < this.formCofig.passwordLength) {
            callback(new Error('至少' + this.formCofig.passwordLength + '个字符'));
          } else {
            callback();
          }
        } else {
          callback();
        }

      }
    };
    let confirmFpsw = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请确认密码'));
      } else {
        if (value != this.ruleForm.fpsw) {
          callback(new Error('两次密码输入不一致'));
        } else {
          callback();
        }
      }
    }
    return {
      height: "calc(100vh - 290px)",
      tableData: [],
      formData: {
        keyWord: ""
      },
      formCofig: {
        ssoSessionMaxLifespan: '',
        ssoSessionIdleTimeout: '',
        passwordLength: '',
        passwordRules: []
      },
      radioId: "",
      tableLoading: false,
      ruleForm: {
        faccount: "",//用户名
        fpsw: "",//密码
        fsignature: "1",//是否有效
        fdescription: "",//备注
        frealName: "",
        confirmFpsw: "", //确认密码
      },
      rules: {
        faccount: [{ required: true, message: '用户不能为空', trigger: 'blur' }],
        fpsw: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: fpsw, trigger: 'blur' }
        ],
        confirmFpsw: [{ validator: confirmFpsw, trigger: 'blur' }],
        fsignature: [{ required: true, message: '请选择是否有效', trigger: 'change' }],
        frealName: [{ required: true, message: '姓名不能为空', trigger: 'change' }],
      },
      isShowAdd: false,
      options: [{
        label: "管理员",
        value: "1"
      }, {
        label: "用户",
        value: "2"
      }],
      title: this.$t('dialog.user_add'),
      loading: false,
      isvalidList: [{
        label: "无效",
        value: "0"
      }, {
        label: "有效",
        value: "1"
      }],
      oldPassWord: "",
      disabled: false,
      pager: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
        field: '',
        order: '',
      }
    }
  },
  created () {
    this.getSysUserList(),
      this.findBasicConfig()
  },
  methods: {
    handleSearch () {
      this.getSysUserList()
    },
    findBasicConfig () {
      siteConfig.findBasicConfig().then(res => {
        if (res.code == 200) {
          res.data.passwordRules = res.data.passwordRules.split(',')
          this.formCofig = res.data
        }
      })
    },
    getSysUserList () {
      const param = {
        faccount: this.formData.keyWord,
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        field: this.pager.field,
        order: this.pager.order,
      }
      this.tableLoading = true
      userAdmin.getSysUserList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.tableData = res.data.rows
          this.pager.total = res.data.total
          this.tableData.forEach(item => {
            item.fsignature = item.fsignature == '1' ? true : false
          })
        }
      }).catch(e => {
        this.tableLoading = false
        this.$message.error('服务器繁忙,请稍后再试');
      })
    },
    sortChange (column) {
      let field = ''
      if (column.prop == 'faccount') {
        field = 'fAccount'
      } else if (column.prop == 'frealName') {
        field = 'fRealName'
      }
      if (column.order === 'descending') {
        this.pager.field = field
        this.pager.order = 'DESC'
      } else {
        this.pager.field = field
        this.pager.order = 'ASC'
      }
      this.pager.pageNum = 1
      this.getSysUserList()
    },
    rowClick (row) {
      this.radioId = row.fid
      this.$refs.refTable.setCurrentRow(row);
    },
    handleAdd () {
      this.title = this.$t('dialog.user_add')
      this.ruleForm = {
        faccount: "",//用户名
        fpsw: "",//密码
        fsignature: "1",//是否有效
        fdescription: "",//备注
        frealName: ""
      }
      try {
        this.$refs['ruleForm'].resetFields();
      } catch (e) { }

      this.isShowAdd = true
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = Object.assign({}, this.ruleForm)
          delete param.confirmFpsw
          if (this.title == this.$t('dialog.user_edit')) {
            if (this.oldPassWord == param.fpsw) {
              delete param.fpsw
            }
          }
          this.loading = true
          userAdmin.addSysUser(param, this.title).then(res => {
            this.loading = false
            if (res.code == 200) {
              this.oldPassWord = ''
              this.isShowAdd = false
              this.getSysUserList()
            } else {
              this.$message.error(res.msg);
            }
          }).catch(e => {
            if (this.title == this.$t('dialog.user_edit')) {
              this.$message.error('编辑失败');
            } else {
              this.$message.error('新增失败');
            }

            this.loading = false
          })
        }
      })
    },
    handleClose () {
      this.isShowAdd = false
    },
    handleEdit () {
      if (this.radioId === '') {
        this.$message.error(this.$t('dialog.please_sel_edit'));
        return
      }
      userAdmin.findSysUser(this.radioId).then(res => {
        if (res.code == 200) {
          this.title = this.$t('dialog.user_edit')
          this.oldPassWord = res.data.fpsw
          Object.assign(this.ruleForm, res.data)
          this.ruleForm.confirmFpsw = res.data.fpsw
          this.isShowAdd = true
        }
      })
    },
    handleDel () {
      if (this.radioId === '') {
        this.$message.error(this.$t('dialog.please_sel_del'));
        return
      }
      let that = this
      const el = this.tableData.find(item => item.fid == this.radioId)
      userAdmin.findSysUser(this.radioId).then(res => {
        if (res.code == 200) {
          this.$customConfirm({
            content: this.$t('dialog.del_meter') + el.faccount,
            onok () {
              userAdmin.removeSysUser(that.radioId).then(res => {
                if (res.code == 200) {
                  that.radioId = ""
                  that.getSysUserList()
                  that.$message({ duration: 1000, type: 'success', message: this.$t('common.del_succ') });
                }
              })
            }
          })
        }
      })
    },
    handleSwitch (row) {
      let param = Object.assign({}, row)
      param.fsignature = row.fsignature == false ? "0" : "1"
      delete param.fpsw
      this.disabled = true
      userAdmin.addSysUser(param, '编辑用户').then(res => {
        this.disabled = false
        if (res.code == 200) {
          this.oldPassWord = ''
          this.getSysUserList()
        }
      }).catch(e => {
        this.disabled = false
      })
    },
    handleSizeChange (val) {
      this.pager.pageNum = 1
      this.pager.pageSize = val
      this.getSysUserList()
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val;
      this.getSysUserList()
    },
    table_index (index) {
      return (this.pager.pageNum - 1) * this.pager.pageSize + index
    },
  }
}
</script>
<style scoped>
.btngroup {
  float: right;
  padding-right: 15px;
  line-height: 0;
}
.adminSelect >>> .el-select {
  width: 100%;
}
</style>